import fastifySession from '@fastify/session';
import fastifyCacheman from 'fastify-cacheman';
import fp from 'fastify-plugin';

declare module 'fastify' {
    interface FastifyInstance {
        setCache: <T>(key: string, data: T, expires: number, useScoped: boolean) => Promise<T>;
        getCache: <T>(key: string, useScoped: boolean) => Promise<T>;
    }
}

export default fp(function (fastify, opts, done) {
    fastify.register(fastifyCacheman, { engine: 'memory' });

    fastify.decorate('setCache', function<T>(key: string, data: T, expires = 3600 * 5, useScoped = false) {
        return new Promise((resolve, reject) => {
            const retKey = useScoped ? `${this.user?.id}_${key}` : key;
            fastify.cacheman.set(retKey, data, expires, (err: Error, value: T) => {
                if (err) {
                    return reject(err);
                }
                resolve(value);
            });
        });
    });

    fastify.decorate('getCache', function<T>(key: string, useScoped = false) {
        return new Promise((resolve, reject) => {
            const retKey = useScoped ? `${this.user?.id}_${key}` : key;
            fastify.cacheman.get(retKey, (err: Error, value: T) => {
                if (err) {
                    return reject(err);
                }
                resolve(value);
            });
        });
    });

    done();
});